import {
  Component,
  OnInit,
  ElementRef,
  ViewChild,
  ViewChildren,
  AfterViewInit,
  Renderer,
  SimpleChanges,
  OnDestroy
} from '@angular/core';
import {Http} from '@angular/http';
import {DatePipe} from '@angular/common';

import {Table, TableRow, TableColomn, TableCell} from './table.model';
import {TagData} from '../../../entity/tag-data.model';
import {List} from 'linqts';
import {DataSourceService} from '../../../service/data-source/data-source.service';
import {TurbStatusService} from '../../../service/turbstatus.service';
import {TurbStatus} from '../../../entity/turbstatus.model';
import {Tag} from '../../../entity/tag.model';
import {ApplicationService} from '../../../service/application.service';
import {Device} from '../../../entity/device.model';
import {FarmCategoryEnum} from '../../common/device-tag-selector/farm-category.enum';
import {DeviceCategoryEnum} from '../../common/device-tag-selector/device-category.enum';
import {RunStopsService} from '../../../service/run-stops.service';
import {RunStop} from '../../../entity/run-stop.model';
import {InterceptorService} from '../../../service/interceptor/interceptor-service';

@Component({
  selector: 'app-turbine-data-list',
  templateUrl: './turbine-data-list.component.html',
  styleUrls: ['./turbine-data-list.component.css']
})
export class TurbineDataListComponent implements OnInit, OnDestroy {
  /**
   * 数据源服务
   *
   * @private
   * @type {DataSourceService}
   * @memberof TurbineListComponent
   */
  private dataSource: DataSourceService;

  /**
   * table td元素集合
   *
   * @type {ElementRef[]}@memberof TurbineDataListComponent
   */
  @ViewChildren('td')
  private td: ElementRef[];
  /**
   * table th元素集合
   *
   * @type {ElementRef[]}@memberof TurbineDataListComponent
   */
  @ViewChildren('th')
  private th: ElementRef[];
  /**
   * table元素集合
   *
   * @type {ElementRef[]}@memberof TurbineDataListComponent
   */
  @ViewChild('main', {static: true})
  private main: ElementRef;
  /**
   * 生成的table集合
   *
   * @type {Table[] }@memberof TurbineDataListComponent
   */
  public turbTable: Table[] = [];
  /**
   * 生成的table集合的th
   *
   * @type {string[]}@memberof TurbineDataListComponent
   */
  private title: string[] = [];
  /**
   * 生成的table集合的row集合
   *
   * @type {TableRow[]}@memberof TurbineDataListComponent
   */
  private tableRow: TableRow[] = [];

  /**
   * 测点对象集合
   *
   * @type {Tag[]}@memberof TurbineDataListComponent
   */
  private tags: Tag[];
  /**
   * 定时器
   *
   * @type {any}@memberof TurbineDataListComponent
   */
  private timer: any = null;
  private unit: string[] = [];
  private devices: Device[] = [];
  public codeTags: string[];
  public defaultChooseDeviceCount: number = 20;
  /**
   * 风机状态集合
   *
   * @type {TurbId}@memberof TurbineDataListComponent
   */
  private turbineStatus: TurbStatus[];
  public farmId = 0;
  //public farmCategory = FarmCategoryEnum.photovoltaic;
  public deviceCategories: DeviceCategoryEnum[] = [DeviceCategoryEnum.inverter, DeviceCategoryEnum.turbine];
  /**
   * plc状态code
   *
   * @type {string}
   * @memberof TurbineDataListComponent
   */
  opeStaIntCode: string = '';
  /**
   * 风机状态code
   *
   * @type {string}
   * @memberof TurbineDataListComponent
   */
  turbineStatuCode: string = '';
  /**
   * plc状态列表
   *
   * @type {RunStop[]}
   * @memberof TurbineDataListComponent
   */
  runStops: RunStop[] = [];
  /**
   *设备选择最大数量
   *
   * @type {number}
   * @memberof TurbineDataListComponent
   */
  public deviceCountLimit: number;

  public orderFlag: string = '';

  constructor(
    private http: InterceptorService,
    private datePipe: DatePipe,
    private elementRef: ElementRef,
    private renderer: Renderer,
    private TurbStatusService: TurbStatusService,
    private application: ApplicationService,
    private runStopsService: RunStopsService
  ) {
  }

  public ngOnInit() {
    if (this.application.currentMenuParams && this.application.currentMenuParams['deviceCountLimit']) {
      this.deviceCountLimit = Number(this.application.currentMenuParams['deviceCountLimit'].paramValue);
    } else {
      this.deviceCountLimit = null;
    }
    if (this.application.currentMenuParams && this.application.currentMenuParams['codeTags']) {
      const codeTags = this.application.currentMenuParams['codeTags']['paramValue'];
      const code = codeTags.replace(/；/g, ';');
      this.codeTags = code.split(';');
    } else {
      this.codeTags = [
        'ActivePower',
        'WindSpeed',
        'OpeStaInt',
        'TurbineStatus'];
    }


    this.opeStaIntCode = this.application.tagDict['OpeStaInt'].tagCode;
    this.turbineStatuCode = this.application.tagDict['TurbineStatus'].tagCode;
    /* this.runStopsService.getRunStops()
      .then(res => {
        console.log(res)
        if (res) {
          this.runStops = [...res];
        }
      })
      .catch(err => {
        console.log(err);
      }) */
    if (window.sessionStorage.getItem('turbineStatus')) {
      this.turbineStatus = JSON.parse(window.sessionStorage.getItem('turbineStatus'));
    }
    else {
      this.TurbStatusService.getTurbStatus()
        .then(res => {
          if (res) {
            this.turbineStatus = [...res];
            window.sessionStorage.setItem('turbineStatus', JSON.stringify(this.turbineStatus));
          }
        })
        .catch(err => {
          console.log(err)
        })
    }
  }

  public ngAfterViewChecked() {
    this.onResize();
  }

  public ngOnDestroy(): void {
    if (this.dataSource != null)
      this.dataSource.dispose();
  }

  /**
   *获取list列表
   *
   * @type {limitedTag[]}@memberof TurbineDataListComponent
   */
  private getData() {
    this.turbTable = [];
    this.tableRow = [];
    //创建数据源
    if (this.dataSource != null) {
      this.dataSource.dispose();
    }
    this.dataSource = new DataSourceService(this.http, this.datePipe);

    this.title = ['风场名称', '风机名称'];
    this.unit = [' ', ' ']
    this.tags.forEach((tag, index) => {

      /* if(tag.tagKey=='OpeStaInt'){
        this.opeStaIntIndex=index;

      } */
      let unit: string = tag.tagUnit ? '(' + tag.tagUnit + ')' : ' ';
      this.unit.push(unit)
      this.title.push(`${tag.tagName}`);
    });
    if (this.devices != null && this.devices.length > 0) {
      let groups = new List(this.devices).GroupBy(g => g.farmCode, m => m);
      let farmCodes = Object.getOwnPropertyNames(groups);

      farmCodes.forEach(farmCode => {
        let devicesList = new List<Device>(Object.getOwnPropertyDescriptor(groups, farmCode).value);
        devicesList.ForEach((device, index) => {
          let td: TableColomn[] = [];
          let tr: TableRow = {
            rowIndex: index,
            colomns: td,
          };
          this.tableRow.push(tr);

          //创建风机固定信息列
          let farmName: TableColomn = {
            colomnIndex: 0,
            cell: {
              rowIndex: 0,
              colomnIndex: 0,
              data: device.farmName,
            },
          };
          td.push(farmName);

          let deviceName: TableColomn = {
            colomnIndex: 1,
            cell: {
              rowIndex: index,
              colomnIndex: 1,
              data: device.deviceName,
            },
          };
          td.push(deviceName);

          //创建风机测点列
          this.tags.forEach((tag: Tag, index: number) => {
            let tagData = this.dataSource.binding([farmCode, device.deviceCode], tag);
            tagData.modelId = device.modelId;
            tagData.valueDesc = null;
            let tagName: TableColomn = {
              colomnIndex: index + 2,
              cell: {
                rowIndex: index,
                colomnIndex: index + 2,
                //绑定数据
                data: tagData,
              }
            };
            td.push(tagName);
          });
        })
      });
      if (farmCodes.length > 0) {
        const count = 20;//table的行数
        const rows = 12;//table的列数
        const page = Math.ceil(this.tableRow.length / count);
        const pageTabel = Math.ceil(this.tableRow[0].colomns.length / rows);
        for (let i = 0; i < page; i++) {
          const tableSlice: TableRow[] = this.tableRow.slice(i * count, i * count + count);
          for (let n = 0; n < pageTabel; n++) {
            const title = n ? this.title.slice(0, 2).concat(this.title.slice(n * rows, n * rows + rows - 2)) : this.title.slice(0, rows);
            const tableSliceRows: TableRow[] = [];
            tableSlice.forEach((v, index) => {
              tableSliceRows.push({
                rowIndex: v.rowIndex,
                colomns: n ? v.colomns.slice(0, 2).concat(v.colomns.slice(n * rows, n * rows + rows - 2)) : v.colomns.slice(0, rows),
              });
            });
            this.turbTable.push({
              rows: tableSliceRows,
              th: title,
              unit: this.unit
            });
          }
        }
        ;
        this.dataSource.begin().subscribe(
          next => {

            /*  next.forEach(o => {
               if (o.code.endsWith(this.turbineStatuCode)) {
                 const index = this.turbineStatus.findIndex(t => t.statusValue == o.value);
                 if (index >= 0) {

                   o.valueDesc = this.turbineStatus[index].statusName;
                 }
               }
               if (o.code.endsWith(this.opeStaIntCode)) {
                 const index = this.runStops.findIndex(t => t.runStopCode == o.value && t.modelId == o.modelId);
                 if (index >= 0) {
                   o.valueDesc = this.runStops[index].runStopDesc;
                 }
               }
             }); */

            this.turbTable.forEach(table => {
              table.rows.forEach(value => {
                value.colomns.forEach(coloum => {
                  if (coloum.cell.data.code && coloum.cell.data.code.endsWith(this.turbineStatuCode)) {
                    const index = this.turbineStatus.findIndex(t => t.statusValue == coloum.cell.data.value);
                    if (index >= 0) {
                      coloum.cell.data.valueDesc = this.turbineStatus[index].statusName;
                    }
                  }
                  /*  if (coloum.cell.data.code && coloum.cell.data.code.endsWith(this.opeStaIntCode) && this.runStops) {
                     const index = this.runStops.findIndex(t => t.runStopCode == coloum.cell.data.value && t.modelId == coloum.cell.data.modelId);
                     if (index >= 0) {
                       coloum.cell.data.valueDesc = this.runStops[index].runStopDesc;
                     }
                   } */


                });
              });
              this.tableOrder()

            });
          },
          error => {
            console.log(error);
          }
        );
      }
    }
    //DSJ.HB_DSJ_1_001_OpeStaInt DSJ.HB_DSJ_1_001_TurbineStatus
  }

  /**
   * 改变排序
   * @param item
   * @param index
   */
  public changeTableDesc(item: any, index: any) {
    if (this.orderFlag && this.orderFlag === index + '_asc') {
      this.orderFlag = index + '_desc'
    } else {
      this.orderFlag = index + '_asc'
    }
    this.tableOrder()
  }

  /**
   * 排序
   */
  public tableOrder() {
    this.turbTable.forEach(table => {
      table.rows.forEach(value => {
        let orderOpt = this.orderFlag.split('_');
        if (orderOpt.length === 2) {
          table.rows.sort((a, b) => {
            let ret = 0;
            let valueA = a.colomns[orderOpt[0]].cell.data.value === undefined ? a.colomns[orderOpt[0]].cell.data : a.colomns[orderOpt[0]].cell.data.value
            let valueB = b.colomns[orderOpt[0]].cell.data.value === undefined ? b.colomns[orderOpt[0]].cell.data : b.colomns[orderOpt[0]].cell.data.value
            if (isNaN(valueA) && isNaN(valueB)) {
              ret = valueA > valueB ? 1 : -1
            } else {
              ret = valueA - valueB
            }
            return ret * (orderOpt[1] === 'desc' ? 1 : -1);
          })
        }
      });
    })
  }

  /**
   * 改变table的布局
   *
   * @type {}@memberof TurbineDataListComponent
   */
  public onResize() {
    const mainWidth: number = this.main.nativeElement.offsetWidth - 20;
    this.th.forEach(elem => {
      this.renderer.setElementStyle(elem.nativeElement, 'width', mainWidth / 12 + 'px');
    });
    this.td.forEach(elem => {
      this.renderer.setElementStyle(elem.nativeElement, 'width', mainWidth / 12 + 'px');
    });
  }

  /**
   * 延迟300毫秒
   *
   * @type {}@memberof TurbineDataListComponent
   */
  private setTime() {
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.getData();
    }, 300);
  }

  onSelectedDevicesChange(devices: Device[]) {
    this.devices = devices;
    const modelIds: number[] = [];
    this.devices.filter(device => {
      if (modelIds.indexOf(device.modelId) === -1) {
        modelIds.push(device.modelId);
      }
    });

    this.runStopsService.getRunStopsByModelIds(modelIds)
      .then(res => {
        if (res) {
          this.runStops = [...res];
        }
        ;
      })
      .catch(err => {
        console.log(err);
      });
    if (this.devices != null && this.tags != null) {

      this.setTime();
    }
  }

  selectedTagsChange(tags: Tag[]) {
    this.tags = tags;
    if (this.devices != null) {
      this.setTime();
    }
  }

  // tslint:disable-next-line:eofline
}


// WEBPACK FOOTER //
// ./src/app/module/monitor/turbine-data-list/turbine-data-list.component.ts
